package csc.com.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "Register", urlPatterns= { "/register"})
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = -4238215648469682508L;
	Matcher emailMatcher = null;
	Matcher userNameMatcher = null;
	Pattern emailPattern = Pattern.compile("[a-zA-Z0-9]*@[a-z]{4,}\\.com");
	Pattern userNamePattern = Pattern.compile("[0-9a-zA-z]{5,}");

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		RequestDispatcher rDispatcher = getServletContext().getRequestDispatcher("/register.html");
		rDispatcher.include(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		ArrayList<String> errors = new ArrayList<>();
		String userName = req.getParameter("userName");
		String password = req.getParameter("password");
		String address = req.getParameter("address");
		String email = req.getParameter("email");

		if (!isValidUserName(userName).equals("")) {
			errors.add(isValidUserName(userName));
		}
		if (!isValidPassword(password).equals("")) {
			errors.add(isValidPassword(password));
		}
		if (!isValidAddress(address).equals("")) {
		    errors.add(isValidAddress(address));
		}
		if (!isValidEmail(email).equals("")) {
			errors.add(isValidEmail(email));
		}
		String errorMsg = "";
		if (errors.size() > 0) {
			for (int i=0;i<errors.size();i++) {
				errorMsg += errors.get(i);
			}
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/register.html");
			PrintWriter out = resp.getWriter();
			out.println("<font color=red>" + errorMsg + "</font>");
			rd.include(req, resp);
			
		} else {
			Connection con = (Connection) getServletContext().getAttribute("DBConnection");
			PreparedStatement ps = null;
			try {
				ps = con.prepareStatement("insert into Users(username,password,address, email, countlogin) values (?,?,?,?,?)");
				ps.setString(1, userName);
				ps.setString(2, password);
				ps.setString(3, address);
				ps.setString(4, email);
				ps.setInt(5, 0);
				ps.execute();
				// forward to login page to login
				RequestDispatcher rd = getServletContext().getRequestDispatcher("/registerSuccess.html");
				PrintWriter out = resp.getWriter();
				out.println("<font color=green>Registration successful, please login below.</font>");
				rd.include(req, resp);
			} catch (SQLException e) {
				e.printStackTrace();
				throw new ServletException("DB Connection problem.");
			} finally {
				try {
					ps.close();
				} catch (SQLException e) { }
			}		
		}		
	}
	public String isValidUserName(String input) {
		String errorMsg="";
		if (input.equals("")) {
			errorMsg = "User Name can't be null or empty.<br/>";
		} else {
			userNameMatcher = userNamePattern.matcher(input);
			if (!userNameMatcher.matches()) {
				errorMsg = "User name must be at least 5 characters in length, contains word and digit characters only.<br/>";
			}
		}
		return errorMsg;
	}
	public String isValidPassword(String input) {
		String errorMsg = "";
		if (input.equals("")) {
			errorMsg = "Password can't be null or empty.<br/>";
		} else {
			if (input.length() < 8) {
				errorMsg = "Password must be at least 8 characters in length.<br/>";
			}
		}
		return errorMsg;
	}
	public String isValidAddress(String input) {
		String errorMsg = "";
		if (input.equals("")) {
			errorMsg = "Address can't be null or empty.<br/>";
		} 
		return errorMsg;
	}
	public String isValidEmail(String input) {
		String errorMsg="";
		if (input.equals("")) {
			errorMsg = "Email can't be null or empty.<br/>";
		} else {
			emailMatcher = emailPattern.matcher(input);
			if (!emailMatcher.matches()) {
				errorMsg = "The email address you supplied is invalid.<br/>";
			}
		}
		return errorMsg;
	}
}
